﻿#region Copyright
/**
 * Copyright (c) 2010 EPiServer AB
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
 * subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial 
 * portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
 **/
#endregion

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using EPiServer;
using EPiServer.Common;
using EPiServer.Common.Data;
using EPiServer.Globalization;
using EPiServer.Web.WebControls;

namespace EPiXternal.RelatePlus.WebControls
{
    [Serializable, ToolboxItem(false)]
    public class InputRelatePlusEntityPicker<T> : InputBase where T : FrameworkEntityBase
    {
        public InputRelatePlusEntityPicker(string id, string browsePageUrl)
            : this(id, browsePageUrl, 530, 500)
        { }

        public InputRelatePlusEntityPicker(string id, string browsePageUrl, int dialogWidth, int dialogHeight)
        {
            ID = id;
            BrowsePageUrl = browsePageUrl;
            DialogWidth = dialogWidth;
            DialogHeight = dialogHeight;
        }

        #region Method Overrides
        protected override void CreateChildControls()
        {
            if (!Page.ClientScript.IsClientScriptIncludeRegistered(Page.GetType(), GetType().ToString()))
            {
                Page.ClientScript.RegisterClientScriptInclude(GetType().ToString(), UriSupport.ResolveUrlBySettings("~/EPiXternal/RelatePlus/Scripts/inputRelatePlusEntityPicker.js"));
            }

            CreateDisplayControl();
            Controls.Add(DisplayControl);

            CreateValueControl();
            Controls.Add(ValueControl);

            HtmlInputButton btnPickerPopup = new HtmlInputButton();

            if (!Enabled)
            {
                btnPickerPopup.Attributes["disabled"] = "disabled";
            }

            btnPickerPopup.Value = "...";
            btnPickerPopup.Attributes["class"] = "epismallbutton";
            btnPickerPopup.Attributes["onclick"] = String.Format("EPiXternal.openRelatePlusEntityBrowser('{0}', document.getElementById('{1}').value,'{2}','{3}','{4}','{5}','{6}', '{7}');",
                BrowsePageUrl,
                ValueControl.ClientID,
                HttpUtility.UrlEncode(DisplayValue),
                ValueControl.ClientID,
                DisplayControl.ClientID,
                ContentLanguage.PreferredCulture.Name,
                DialogWidth,
                DialogHeight);

            Controls.Add(btnPickerPopup);
        }
        #endregion

        #region Properties
        public string DisplayValue
        {
            get
            {
                if (DisplayControl != null)
                {
                    return DisplayControl.Text;
                }

                return null;
            }
            set
            {
                CreateDisplayControl();
                DisplayControl.Text = value;
            }
        }

        public T Value
        {
            get
            {
                int entityId;
                if (ValueControl != null && int.TryParse(ValueControl.Value, out entityId))
                {
                    return (T)EntityProviderHandler.GetEntityProvider(typeof(T)).GetEntityInstance(typeof(T), entityId);
                }

                return null;
            }
            set
            {
                CreateValueControl();

                if (value != null)
                {
                    ValueControl.Value = value.ID.ToString();
                }
            }
        }

        public HtmlInputHidden ValueControl
        {
            get;
            private set;
        }

        public TextBox DisplayControl
        {
            get;
            private set;
        }

        public int DialogWidth
        {
            get;
            set;
        }

        public int DialogHeight
        {
            get;
            set;
        }

        public string BrowsePageUrl
        {
            get;
            set;
        }
        #endregion

        #region Private helpers
        private void CreateDisplayControl()
        {
            if (DisplayControl == null)
            {
                DisplayControl = new TextBox();
                DisplayControl.Columns = 20;
                DisplayControl.MaxLength = 20;
                DisplayControl.CssClass = CssClass;
                DisplayControl.AutoPostBack = false;
                DisplayControl.ID = "txtDisplayValue";
                DisplayControl.Enabled = false;

                CopyWebAttributes(DisplayControl);
            }
        }

        private void CreateValueControl()
        {
            if (ValueControl == null)
            {
                ValueControl = new HtmlInputHidden();
                ValueControl.ID = "hdnEntityValue";
            }
        }
        #endregion
    }
}